package cn.iocoder.yudao.module.resource.controller.admin.messagecollection;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.resource.controller.admin.messagecollection.vo.MessageCollectionImportExcelVO;
import cn.iocoder.yudao.module.resource.controller.admin.messagecollection.vo.MessageCollectionPageReqVO;
import cn.iocoder.yudao.module.resource.controller.admin.messagecollection.vo.MessageCollectionRespVO;
import cn.iocoder.yudao.module.resource.controller.admin.messagecollection.vo.MessageCollectionSaveReqVO;
import cn.iocoder.yudao.module.resource.dal.dataobject.messagecollection.MessageCollectionDO;
import cn.iocoder.yudao.module.resource.service.messagecollection.MessageCollectionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.IMPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Slf4j
@Tag(name = "管理后台 - 消息仓库")
@RestController
@RequestMapping("/lm/message-collection")
@Validated
public class MessageCollectionController {

    @Resource
    private MessageCollectionService messageCollectionService;

    @PostMapping("/create")
    @Operation(summary = "创建消息仓库")
    @PreAuthorize("@ss.hasPermission('lm:message-collection:create')")
    public CommonResult<String> createMessageCollection(@Valid @RequestBody MessageCollectionSaveReqVO createReqVO) {
        return success(messageCollectionService.createMessageCollection(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新消息仓库")
    @PreAuthorize("@ss.hasPermission('lm:message-collection:update')")
    public CommonResult<Boolean> updateMessageCollection(@Valid @RequestBody MessageCollectionSaveReqVO updateReqVO) {
        messageCollectionService.updateMessageCollection(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除消息仓库")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('lm:message-collection:delete')")
    public CommonResult<Boolean> deleteMessageCollection(@RequestParam("id") String id) {
        messageCollectionService.deleteMessageCollection(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得消息仓库")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('lm:message-collection:query')")
    public CommonResult<MessageCollectionRespVO> getMessageCollection(@RequestParam("id") String id) {
        MessageCollectionDO messageCollection = messageCollectionService.getMessageCollection(id);
        return success(BeanUtils.toBean(messageCollection, MessageCollectionRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得消息仓库分页")
    @PreAuthorize("@ss.hasPermission('lm:message-collection:query')")
    public CommonResult<PageResult<MessageCollectionRespVO>> getMessageCollectionPage(@Valid MessageCollectionPageReqVO pageReqVO) {
        PageResult<MessageCollectionDO> pageResult = messageCollectionService.getMessageCollectionPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, MessageCollectionRespVO.class));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出消息仓库 Excel")
    @PreAuthorize("@ss.hasPermission('lm:message-collection:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMessageCollectionExcel(@Valid MessageCollectionPageReqVO pageReqVO,
                                             HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MessageCollectionDO> list = messageCollectionService.getMessageCollectionPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "消息仓库.xls", "数据", MessageCollectionRespVO.class,
                BeanUtils.toBean(list, MessageCollectionRespVO.class));
    }

    @PostMapping("/import-excel")
    @Operation(summary = "导入消息仓库 Excel")
    @PreAuthorize("@ss.hasPermission('lm:message-collection:import')")
    @ApiAccessLog(operateType = IMPORT)
    public CommonResult importMessageCollectionExcel(@RequestParam("file") MultipartFile file) throws IOException {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 解析Excel文件
        final List<MessageCollectionImportExcelVO> list = ExcelUtils.read(file, MessageCollectionImportExcelVO.class);
        if (CollUtil.isEmpty(list)) {
            log.warn("Excel数据为空");
            return success(null);
        }

        final AtomicInteger index = new AtomicInteger(0);
        list.parallelStream().forEach(msg -> {
            log.info("开始导入消息, index = {}, size = {}", index.get(), list.size());
            final MessageCollectionSaveReqVO createReqVO = BeanUtils.toBean(msg, MessageCollectionSaveReqVO.class);
            messageCollectionService.createMessageCollection(createReqVO);
            index.incrementAndGet();
        });

        return success(null);
    }
}